package com.heima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.exception.BaseException;
import com.heima.mapper.NodeMapper;
import com.heima.mapper.RegionMapper;
import com.heima.mapper.VendingMachineMapper;
import com.heima.mapper.VmTypeMapper;
import com.heima.pojo.dto.NodeDto;
import com.heima.pojo.dto.NodeSearchDto;
import com.heima.pojo.entity.Node;
import com.heima.pojo.entity.VendingMachine;
import com.heima.pojo.entity.VmType;
import com.heima.pojo.vo.NodeSearchVO;
import com.heima.pojo.vo.NodeVO;
import com.heima.pojo.vo.RegionVo;
import com.heima.pojo.vo.VendingMachineVo;
import com.heima.service.NodeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 点位表 服务实现类
 * </p>
 *
 * @author ljk
 * @since 2024-10-16
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class NodeServiceImpl extends ServiceImpl<NodeMapper, Node> implements NodeService {
    private final NodeMapper nodeMapper;
    private final VmTypeMapper vmTypeMapper;
    private final RegionMapper regionMapper;
    private final VendingMachineMapper vendingMachineMapper;

    @Override
    public NodeSearchVO pageQuery(NodeSearchDto nodeSearchDto) {
        //TODO pageHelper正常完成
        /*PageHelper.startPage(nodeSearchDto.getPageIndex(),nodeSearchDto.getPageSize());
        Page<NodeVO> list = nodeMapper.pageQuery(nodeSearchDto.getRegionId());
        NodeSearchVO nodeSearchVO = NodeSearchVO.builder()
                .pageIndex(String.valueOf(nodeSearchDto.getPageIndex()))
                .pageSize(String.valueOf(nodeSearchDto.getPageSize()))
                .totalCount(String.valueOf(list.getTotal()))
                .totalPage(String.valueOf((int) Math.ceil((double) list.getTotal() / nodeSearchDto.getPageSize())))
                .currentPageRecords(list.getResult())
                .build();
        return nodeSearchVO;*/
        //TODO 尝试 mp分页完成
        IPage<NodeVO> page = new Page<>(nodeSearchDto.getPageIndex(), nodeSearchDto.getPageSize());
        IPage<NodeVO> list = nodeMapper.selectPageVO(page, nodeSearchDto);
        NodeSearchVO nodeSearchVO = NodeSearchVO.builder()
                .pageIndex(String.valueOf(list.getCurrent()))
                .pageSize(String.valueOf(list.getSize()))
                .totalCount(String.valueOf(list.getTotal()))
                .totalPage(String.valueOf(list.getPages()))
                .currentPageRecords(list.getRecords())
                .build();
        return nodeSearchVO;
    }

    @Override
    public void insertNode(NodeDto nodeDto) {
        LambdaQueryWrapper<Node> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Node::getName, nodeDto.getName());
        Node node = nodeMapper.selectOne(queryWrapper);
        if (node != null) {
            throw new BaseException("点位已存在");
        }
        Node newNode = new Node();
        BeanUtils.copyProperties(nodeDto,newNode);
        nodeMapper.insert(newNode);
    }

    /**
     * 根据节点ID获取自动售货机列表
     *
     * @param nodeId 节点ID，用于查询该节点下的所有自动售货机
     * @return 返回一个VendingMachineVo对象列表，包含该节点下所有自动售货机的信息
     * @throws BaseException 如果指定的节点不存在，则抛出异常
     */
    @Override
    public List<VendingMachineVo> vmList(String nodeId) {
        // 根据节点ID查询节点信息
        Node node = nodeMapper.selectById(nodeId);
        // 如果节点不存在，则抛出异常
        if (node==null){
            throw new BaseException("不存在该点位");
        }

        // 创建查询条件，查询属于指定节点的所有自动售货机
        LambdaQueryWrapper<VendingMachine> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(VendingMachine::getNodeId,nodeId);
        List<VendingMachine> vendingMachines = vendingMachineMapper.selectList(queryWrapper1);

        // 如果自动售货机列表为空，则返回null
        if (CollectionUtils.isEmpty(vendingMachines)){
            return null;
        }

        // 提取自动售货机的区域ID和类型ID，用于后续查询区域和类型信息
        List<Long> regionIds = vendingMachines.stream().map(VendingMachine::getRegionId).collect(Collectors.toList());
        List<Integer> vmTypeIds = vendingMachines.stream().map(VendingMachine::getVmType).collect(Collectors.toList());

        // 根据区域ID和类型ID查询区域和类型信息
        List<RegionVo> regions =  regionMapper.selectByIds(regionIds);
        List<VmType> vmTypes = vmTypeMapper.selectByIds(vmTypeIds);
        // 查询节点详细信息
        NodeVO nodeVo = nodeMapper.selectNodeVoById(nodeId);

        // 创建结果列表，用于存储自动售货机的视图对象
        List<VendingMachineVo> resList = new ArrayList<>();
        // 遍历自动售货机列表，创建并填充自动售货机视图对象
        for (VendingMachine vendingMachine : vendingMachines) {
            VendingMachineVo vo = new VendingMachineVo();
            BeanUtils.copyProperties(vendingMachine,vo);
            // 设置自动售货机的类型和区域信息
            vo.setType(vmTypes.stream().filter(o->o.getTypeId().equals(vendingMachine.getVmType())).findFirst().orElse(null));
            vo.setRegion(regions.stream().filter(o->o.getId().equals(vendingMachine.getRegionId())).findFirst().orElse(null));
            vo.setNode(nodeVo);
            resList.add(vo);
        }

        // 记录结果列表的日志信息
        log.info("resList:{}",resList);
        // 返回结果列表
        return resList;
    }

    @Override
    public void updateNode(String nodeId, NodeDto nodeDto) {
        Node node = nodeMapper.selectById(nodeId);
        if (node==null){
            throw new BaseException("点位不存在");
        }
        Node node1 = new Node();
        BeanUtils.copyProperties(nodeDto,node1);
        node1.setId(Long.valueOf(nodeId));
        nodeMapper.updateById(node1);
    }

    @Override
    public void delNode(String nodeId) {
        Node node = nodeMapper.selectById(nodeId);
        if (node==null){
            throw new BaseException("点位不存在");
        }

        List<VendingMachine> VMList = vendingMachineMapper.selectByNodeId(nodeId);
        if (!CollectionUtils.isEmpty(VMList)){
            throw new BaseException("该点位还有设备，不能删除");
        }

        nodeMapper.deleteById(nodeId);
    }
}
